package com.ailk.kbi.kbiwarden.wsi.util





import groovy.xml.MarkupBuilder

import java.io.File

import com.ailk.kbi.kbiwarden.wsi.type.request.ConditionsType;
import com.ailk.kbi.kbiwarden.wsi.type.request.AuthInfoType;
import com.ailk.kbi.kbiwarden.wsi.vo.QueryVO
import com.ailk.kbi.kbiwarden.wsi.vo.SessionVO




/**
 * 异步工具类
 */
class AsynUtil {
	/**
	 * 
	 * @param login
	 * @param dataBaseName
	 * @param tableName
	 * @param dim
	 * @param notifyAddress
	 * @return
	 */
	static String startAsynData(AuthInfoType login, String dataBaseName, String tableName,ConditionsType conditions, String notifyAddress){
		DataUtil dataUtil = new DataUtil()
		QueryVO queryVO = dataUtil.getQueryVO(dataBaseName, tableName, conditions)
		int maxCount = dataUtil.getMaxCountResult(queryVO)
		int delay = 0;
		if(maxCount > 100){
			delay = maxCount / 100 + 5
		}

		SessionVO sessionVO = SessionHandler.newSession(login,queryVO,notifyAddress)
		AsynDataThread asynData = new AsynDataThread(sessionVO)
		asynData.start()
		def writer = new StringWriter()
		def xml = new MarkupBuilder( writer )

		xml.result {
			xml.maxCount(maxCount)
			xml.delay(delay)
			xml.sessionId(sessionVO.sessionId)
		}
		writer.toString()
	}

	static String getDataXML(String sessionId){
		SessionVO session = SessionHandler.getSession(sessionId)
		if(session.isComplete){
			String content = getXmlContent(session)
			deleteXmlFile(session)
			SessionHandler.deleteSession(sessionId)
			content
		}
		else{
			throw new Exception("数据未创建完成");
		}
	}

	static String getXmlFileName(SessionVO sessionVO){
		SystemUtil.getWebRoot() + sessionVO.sessionId + ".xml"
	}

	static String getXmlContent(SessionVO sessionVO){
		String fileName = getXmlFileName(sessionVO)
		String content = (new File(fileName)).getText();
		content;
	}

	static String deleteXmlFile(SessionVO sessionVO){
		String fileName = getXmlFileName(sessionVO)
		File file = new File(fileName)
		if(file.exists()){
			file.delete();
		}
	}
}
